<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <title>图像超分辨率示例</title>
    <style>
        h1, h3 {
            font-weight: normal;
        }

        #msg {
            margin: 15px 0;
        }
    </style>
</head>
<body>

<h1>图像超分辨率</h1>
<div class="main">
    <section>
        <a href="https://cloud.tencent.com/document/product/436/83800" target="_blank">COS图像超分辨率文档链接</a>
    </section>
    <section>
        <h3>使用方式一、下载时，处理桶里的对象：</h3>
        <button id="file1">选择本地文件</button>
    </section>
    <section>
        <h3>使用方式二、下载时，传入 Url 处理：</h3>
        <input id="url2" type="text" placeholder="输入图片 URL 或上传文件"
               style="padding:2px 5px;vertical-align:bottom;width:320px"/>
        <button id="submit2">提交 Url 处理</button>
    </section>
    <section>
        <h3>使用方式三、上传时，传参处理和转存：</h3>
        <button id="file3">选择本地文件</button>
    </section>
    <div id="msg"></div>
    <div id="before"></div>
    <div id="after"></div>
</div>

<script>
    // 获取某个 id 的元素
    const $g = function (id) {
        return document.getElementById(id);
    };
    // 提示消息
    const $tips = {
        message: function (msg, type) {
            const colorMap = {
                'success': 'green',
                'error': 'red',
            };
            const color = colorMap[type];
            const styleStr = color ? ` style="color:${color}"` : '';
            $g('msg').innerHTML = `<span${styleStr}>${msg}</span>`;
        },
        success: function (msg) {
            $tips.message(msg, 'success');
        },
        error: function (msg) {
            $tips.message(msg, 'error');
        },
    };

    // 发请求的方法
    const request = function (opt, callback) {
        const {method = 'GET', url, headers, body} = opt;
        const xhr = new XMLHttpRequest();
        xhr.open(method || 'GET', url, true);
        if (typeof headers === 'object') {
            Object.keys(headers).forEach(function (headerKey) {
                xhr.setRequestHeader(headerKey, headers[headerKey]);
            });
        }
        const getXhrRes = function () {
            return {
                statusCode: xhr.status,
                statusMessage: xhr.statusText,
                body: xhr.responseText,
            }
        };
        xhr.onerror = function () {
            callback(getXhrRes());
        };
        xhr.onload = function () {
            callback(null, getXhrRes());
        };
        xhr.send(body);
    };

    // 加载原图和处理以后的图
    const showImages = function (url1, url2) {
        $g('before').innerHTML = `原图：<br/><img src="${url1}"/>`;
        $g('after').innerHTML = `图片超分辨率图处理后的图：<br/><img src="${url2}"/>`;
    };

    // 方式一、下载时处理，上传文件后，下载时加上图像超分参数
    $g('file1').onclick = function () {
        const input = document.createElement('input');
        input.type = 'file';
        input.onchange = function () {
            const file = input.files[0];
            if (file) {
                const dotIndex = file.name.lastIndexOf('.');
                if (dotIndex === -1) return $tips.error('文件格式错误！');
                const ext = file.name.slice(dotIndex + 1);
                $tips.message('正在上传...');
                request({
                    method: 'GET',
                    url: `/api/sign/upload?ext=${ext}`,
                }, function (err, data) {
                    if (err) return $tips.error(`获取上传签名失败！${err.statusCode} ${err.statusMessage}`);
                    const signResult = JSON.parse(data.body);
                    if (signResult.code) return $tips.error(`获取上传签名失败！code:${signResult.code}(${signResult.message})`);
                    const {signedUrl, objectUrl, downloadUrl, authorization, securityToken} = signResult.data;
                    request({
                        method: 'PUT',
                        url: objectUrl,
                        body: file,
                        headers: {
                            'Authorization': authorization,
                            'x-cos-security-token': securityToken,
                        },
                    }, function (err, data) {
                        if (err) return $tips.error(`${err.statusCode} ${err.statusMessage}`);
                        if (data.statusCode !== 200) return $tips.error(`${data.statusCode} ${data.statusMessage}`);
                        else $tips.success('文件上传成功！');
                        // 加载原图和处理以后的图
                        showImages(downloadUrl, downloadUrl + '&ci-process=AISuperResolution');
                        // 设置到方式2里，方便体验
                        $g('url2').value = downloadUrl;
                    });
                });
            }
        };
        input.click();
    };

    // 方式二、下载时处理，实现上传文件，得到 URL
    // 提交 url，做图像超分辨率处理
    $g('submit2').onclick = async function () {
        const url = $g('url2').value;
        // 获取签名
        request({
            method: 'GET',
            url: `/api/sign/AISuperResolution2`,
        }, function (err, data) {
            if (err) return $tips.error(`获取下载时签名失败！${err.statusCode} ${err.statusMessage}`);
            const signResult = JSON.parse(data.body);
            if (signResult.code) return $tips.error(`获取下载时签名失败！code:${signResult.code}(${signResult.message})`);
            const {signedUrl} = signResult.data;
            const superUrl = `${signedUrl}&ci-process=AISuperResolution&detect-url=${encodeURIComponent(url)}`
            // 加载原图和处理以后的图
            showImages(url, superUrl)
        });
    };

    // 方式三、上传时处理，实现上传文件，得到 URL
    $g('file3').onclick = function () {
        const input = document.createElement('input');
        input.type = 'file';
        input.onchange = function () {
            const file = input.files[0];
            if (file) {
                const dotIndex = file.name.lastIndexOf('.');
                if (dotIndex === -1) return $tips.error('文件格式错误！');
                const ext = file.name.slice(dotIndex + 1);
                $tips.message('正在上传...');
                request({
                    method: 'GET',
                    url: `/api/sign/upload?ext=${ext}`,
                }, function (err, data) {
                    if (err) return $tips.error(`获取上传签名失败！${err.statusCode} ${err.statusMessage}`);
                    const signResult = JSON.parse(data.body);
                    if (signResult.code) return $tips.error(`获取上传签名失败！code:${signResult.code}(${signResult.message})`);
                    const {signedUrl, objectUrl, downloadUrl, authorization, securityToken} = signResult.data;
                    const targetKey = objectUrl.replace(/^https?:\/\/[^/]+\/(.*)\.([^.]+)$/, '$1.super.$2');
                    const picOperations = {
                        rules: [{
                            fileid: '/' + targetKey,
                            rule: "ci-process=AISuperResolution"
                        }]
                    };
                    request({
                        method: 'PUT',
                        url: signedUrl,
                        body: file,
                        headers: {
                            'Pic-Operations': JSON.stringify(picOperations),
                            'Authorization': authorization,
                            'x-cos-security-token': securityToken,
                        },
                    }, function (err, data) {
                        if (err) return $tips.error(`图片超分处理失败！${err.statusCode} ${data.statusMessage}`);
                        if (data.statusCode !== 200) return $tips.error(`图片超分处理失败！${data.statusCode} ${data.statusMessage}`);
                        $tips.success('图片超分处理成功！');
                        // 获取签名
                        request({
                            method: 'GET',
                            url: `/api/sign/download?key=${encodeURIComponent(targetKey)}`,
                        }, function (err, data) {
                            if (err) return $tips.error(`获取签名失败！${err.statusCode} ${err.statusMessage}`);
                            const signResult = JSON.parse(data.body);
                            if (signResult.code) return $tips.error(`获取签名失败！code:${signResult.code}(${signResult.message})`);
                            const {signedUrl: superUrl} = signResult.data;
                            // 加载原图和处理以后的图
                            showImages(downloadUrl, superUrl);
                        });
                    });
                });
            }
        };
        input.click();
    };
</script>

</body>
</html>


